package com.lvyq.wx.util;

import com.alibaba.fastjson.JSONObject;
import com.lvyq.constant.WeChatCgiBinConstant;
import com.lvyq.util.HttpRequestUtil;
import com.lvyq.wx.model.Message;

/**
 * @author lvyq
 * @version 1.0
 * @description: TODO
 * @date 2021/2/22 17:07
 */
public class MsgUtil {
    /**
     * 公众号推送封装
     *
     * @param vo
     * @param accessToken
     * @throws Exception
     */
    public static JSONObject sendMessagePush(Message vo, String accessToken) {
        JSONObject mav = new JSONObject();
        JSONObject json = new JSONObject();
        JSONObject text = new JSONObject();
        JSONObject first = new JSONObject();
        JSONObject remark = new JSONObject();
        if (vo.getToUser() == null || vo.getTemplateId() == null) {
            mav.put("state", false);
            mav.put("msg", "参数不足");
            return mav;
        }
        json.put("touser", vo.getToUser());
        json.put("template_id", vo.getTemplateId());
        json.put("url", vo.getSmUrl());
        first.put("value", vo.getTitle());
        remark.put("value", vo.getRemark());
        if (vo.getKeyword1() != null) {
            JSONObject keyword1 = new JSONObject();
            keyword1.put("value", vo.getKeyword1());
            text.put("keyword1", keyword1);
        }
        if (vo.getKeyword2() != null) {
            JSONObject keyword2 = new JSONObject();
            keyword2.put("value", vo.getKeyword2());
            text.put("keyword2", keyword2);
        }
        if (vo.getKeyword3() != null) {
            JSONObject keyword3 = new JSONObject();
            keyword3.put("value", vo.getKeyword3());
            text.put("keyword3", keyword3);
        }
        if (vo.getKeyword4() != null) {
            JSONObject keyword4 = new JSONObject();
            keyword4.put("value", vo.getKeyword4());
            text.put("keyword4", keyword4);
        }
        if (vo.getKeyword5() != null) {
            JSONObject keyword5 = new JSONObject();
            keyword5.put("value", vo.getKeyword5());
            text.put("keyword5", keyword5);
        }
        if (vo.getTitleColor() != null) {
            first.put("color", vo.getTitleColor());
        }
        if (vo.getRemarkColor() != null) {
            remark.put("color", vo.getRemarkColor());
        }
        //小程序
        if (vo.getSmAppId() != null) {
            JSONObject miniprogram = new JSONObject();
            miniprogram.put("appid", vo.getSmAppId());
            miniprogram.put("pagepath", vo.getSmPagePath());
            json.put("miniprogram", miniprogram);
        }
        text.put("first", first);
        text.put("remark", remark);
        json.put("data", text);
        //发送模板消息
        String sendUrl = WeChatCgiBinConstant.MESSAGE_TEMP_SEND;
        sendUrl = sendUrl.replace("ACCESS_TOKEN", accessToken);
        String jsonStringParm = json.toString();
        mav = HttpRequestUtil.httpsRequest(sendUrl, "POST", jsonStringParm);
        return mav;
    }

}
